package com.ruoyi.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.api.service.SelectCustomers;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;

import com.ruoyi.common.utils.WXShiroUtils;
import com.ruoyi.company.domain.*;
import com.ruoyi.company.service.*;
import com.ruoyi.company.utils.Util;
import com.ruoyi.sale.domain.SaleorderOrder;
import com.ruoyi.sale.service.ISaleorderService;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * wx 查询客户信息
 */
@Controller
@RequestMapping("/wx/business/selectCustomers")
public class SelectCustomersController extends BaseController {

    @Autowired
    private SelectCustomers selectCustomers;
    @Autowired
    ISaleorderService iSaleorderService;

    @Autowired
    ICompanyServer iCompanyServer;

    @Autowired
    ICompanyInvoiceService iCompanyInvoiceService;

    @Autowired
    ICompanyMyLinkmanServer iCompanyMyLinkmanServer;
    @Autowired
    ISysDeptService iSysDeptService;

    @Autowired
    ICompanyOtherServer iCompanyOtherServer;

    @Autowired
    ICompanyLinkmanServer iCompanyLinkmanServer;


    /**
     * 查询 合作单位 列表 只展示当前登陆人的合作单位
     */
    @PostMapping("/selectCustomers")
    @ResponseBody
    public TableDataInfo list(String deptName) {
        startPage();
        SysUser user = WXShiroUtils.getSysUser();
        Long companyId = user.getCompanyId();
        //定义查询集合
        Map<String, Object> map = new HashMap();
        if (!user.getDeptId().equals(companyId)) {
            map.put("customerForStaff", user.getUserId());
        }
        map.put("deptId", companyId);
        if (deptName != null && deptName != "") {
            map.put("deptName", deptName);
        }
        List<CompanyOther> list = selectCustomers.selectList(map);

        return getDataTable(list);
    }

    /**
     * 经营范围 展示数据
     *
     * @return 返回设置公司经营范围的数据 TableDataInfo
     */
    @PostMapping("/lookScopeList")
    @ResponseBody
    public TableDataInfo showScopeList(Long companyId, String scopeClass) {
        startPage();
        Map<String, Object> map = new HashMap<>();
        map.put("companyId", companyId);
        if (scopeClass == null || scopeClass == "") {
            map.put("scopeClass", "0");
        } else {
            map.put("scopeClass", scopeClass);
        }

        List<CompanyScope> list = selectCustomers.selectScopeList(map);
        return getDataTable(list);
    }



    @PostMapping("/dataIntoContract")
    @ResponseBody
    public JSONObject dataIntoContract(Long saleorderId, ServletRequest request) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("saleorderId", saleorderId);
        hashMap.put("deptId", WXShiroUtils.getSysUser().getCompanyId());
//        SaleorderOrder saleorderOrder W= iSaleorderService.selectSaleorderById(hashMap);
        SaleorderOrder saleorderOrder = iSaleorderService.selectSaleorderByIdMap(hashMap);
        Company company = iCompanyServer.selectByCompanyId(saleorderOrder.getDeptId());

        //需方 信息;
        Company demanderData = iCompanyServer.selectByCompanyId(saleorderOrder.getCompanyId());
        CompanyInvoice demanderInvoiceData = iCompanyInvoiceService.selectByCompanyId(saleorderOrder.getCompanyId());
        Map<String, Object> linkMap = new HashMap<>();
        linkMap.put("deptId", WXShiroUtils.getSysUser().getCompanyId());
        linkMap.put("companyId", saleorderOrder.getCompanyId());
        List<CompanyLinkman> companyLinkmen = iCompanyLinkmanServer.selectLinkman(linkMap);
        CompanyLinkman companyLinkman = companyLinkmen.get(0);

        //供方 信息;
        Company purchaseData = iCompanyServer.selectByCompanyId(saleorderOrder.getDeptId());
        CompanyInvoice purchaseInvoiceData = iCompanyInvoiceService.selectByCompanyId(saleorderOrder.getDeptId());

        Map<String, Object> myLinkMap = new HashMap<>();
        myLinkMap.put("deptId", WXShiroUtils.getSysUser().getCompanyId());
        List<CompanyMyLinkman> companyMyLinkmen = iCompanyMyLinkmanServer.selectLinkman(linkMap);
        CompanyMyLinkman companyMyLinkman = new CompanyMyLinkman();
        if (companyMyLinkmen.size() != 0) {
            companyMyLinkman = companyMyLinkmen.get(0);
        }
        JSONObject jsonObject = new JSONObject();
        //合同编号 是销售订单的编号
        jsonObject.put("contractNo", saleorderOrder.getSaleorderNum());
        //供方
        jsonObject.put("purchaseName", iSysDeptService.selectDeptById(saleorderOrder.getDeptId()).getDeptName());
        //签订日期 contractDate
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        jsonObject.put("contractDate", fmt.format(saleorderOrder.getSaleorderDate()));
        //需方
        jsonObject.put("demander", iSysDeptService.selectDeptById(saleorderOrder.getCompanyId()).getDeptName());
        //签订地点
        Map map = new HashMap();
        map.put("deptId", saleorderOrder.getDeptId());
        map.put("companyId", saleorderOrder.getCompanyId());
        map.put("gradeStatus", "02");
        CompanyOther companyOther = iCompanyOtherServer.selectByCompanyIdAndDeptId(map);
        if (companyOther == null) {
            new AjaxResult(AjaxResult.Type.ERROR, "您还没有建立与该合作单位的合作关系，请在基础信息-合作单位管理菜单模块建立合作关系。");
            throw new RuntimeException("您还没有建立与该合作单位的合作关系，请在基础信息-合作单位管理菜单模块建立合作关系。");
        }
        jsonObject.put("contractAddress", company.getCity());
        //销售订单产品
        JSONArray jsonArrayModel = new JSONArray();
        for (int i = 0; i < saleorderOrder.getSaleorderModels().size(); i++) {
            jsonArrayModel.add(saleorderOrder.getSaleorderModels().get(i));
        }
        jsonObject.put("models", jsonArrayModel);
        //总数量
        int totalNum = 0;
        for (int i = 0; i < saleorderOrder.getSaleorderModels().size(); i++) {
            totalNum += saleorderOrder.getSaleorderModels().get(i).getNum();
        }
        jsonObject.put("totalNum", totalNum);
        //总金额
        jsonObject.put("totalMoney", saleorderOrder.getSaleorderTaxamount());
        //合计人民币
        BigDecimal taxamount = saleorderOrder.getSaleorderTaxamount();
        double saleorderTaxamount = taxamount.doubleValue();
//        jsonObject.put("upperMoney", upperCase(saleorderTaxamount));
        jsonObject.put("upperMoney", Util.upperCases(saleorderTaxamount));
        //合同约定项
        JSONArray jsonContractTerms = new JSONArray();
        String contractTerms = companyOther.getContractTerms();
        //根据回车进行分割
        String[] contractTermsArr = new String[]{};
        if (!"".equals(contractTerms) && contractTerms != null) {
            contractTermsArr = contractTerms.split("\\r?\\n");
        }
        for (int i = 0; i < contractTermsArr.length; i++) {
            String str = contractTermsArr[i];
            jsonContractTerms.add(str);
        }
        jsonObject.put("contractTerms", jsonContractTerms);

        //供货单位
        //地址
        jsonObject.put("purchaseAddress", purchaseData.getProvince() + purchaseData.getCity() + purchaseData.getOtherCorporateAddress());

        //印章
        String purSeal = "";
        if (purchaseData.getElectronicSealUrl() != null && !"".equals(purchaseData.getElectronicSealUrl())) {
            purSeal = purchaseData.getElectronicSealUrl();
            purSeal = purSeal.split("/profile/upload")[1];
            try {
                purSeal = Util.encodeToString(RuoYiConfig.getUploadPath() + purSeal);
            } catch (IOException e) {
                e.printStackTrace();
            }
//            try {
//                purSeal = Util.encodeToString(RuoYiConfig.getDownloadPath() + purSeal);
//                String downloadPath = RuoYiConfig.getDownloadPath();
//                File file = new File(downloadPath);
//                if (!file.exists()) {
//                    file.mkdir();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        } else {
//            if (purchaseData.getSealUrl() != null && !"".equals(purchaseData.getSealUrl())) {
//                purSeal = purchaseData.getSealUrl();
//            } else {
////                //生成电子印章到服务器
////                //自动生成一个印章 上传到服务器上
////                String socialCreditCode = purchaseData.getSocialCreditCode();
////                String imgname = socialCreditCode + ".png";
////                String downloadPath = RuoYiConfig.getDownloadPath();
////                File file = new File(downloadPath);
////                if (!file.exists()) {
////                    file.mkdir();
////                }
////                File pngfile = new File(downloadPath + "/seal");
////                if (!pngfile.isDirectory()) {
////                    pngfile.mkdir();
////                }
////                String path = downloadPath + "seal/" + imgname;
////                //生成 印章照片
////                try {
////                    SealUtils.toSeal(iSysDeptService.selectDeptById(purchaseData.getCompanyId()).getDeptName(), purchaseData.getSocialCreditCode(), path);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                }
////                Company company2 = new Company();
////                company2.setSealUrl("/seal/" + imgname);
////                company2.setCompanyId(purchaseData.getCompanyId());
////                purSeal = "/seal/" + imgname;
////                //更新url
////                iCompanyServer.updateCompany(company2);
//            }
////            //将图片 转为64位 返回
////            try {
////                purSeal = Util.encodeToString(RuoYiConfig.getDownloadPath() + purSeal);
////            } catch (IOException e) {
////                e.printStackTrace();
////            }
        }

        if (!purSeal.equals("")) {
            jsonObject.put("purSeal", "data:image/jpg;base64," + purSeal);
        }

        //邮编

        //电话
//        jsonObject.put("purchasePhone", purchaseInvoiceData.getCorporateRegisterPhone());
        jsonObject.put("purchasePhone", companyMyLinkman.getPhoneNum());
        //统一社会信用代码
        jsonObject.put("purchaseSocialCreditCode", purchaseData.getSocialCreditCode());
        //开户
        jsonObject.put("purchaseBank", purchaseInvoiceData.getDepositBank());
        //账号
        jsonObject.put("purchaseBankNum", purchaseInvoiceData.getBankNumber());
        //签约代表
//        jsonObject.put("purchaseCustomerForStaff", purchaseData.getCorporateRepresentative());
        jsonObject.put("purchaseCustomerForStaff", companyMyLinkman.getName());

        //供货单位

        //地址
        jsonObject.put("demanderAddress", demanderData.getProvince() + demanderData.getCity() + demanderData.getOtherCorporateAddress());

        //印章
        String demanderSeal = "";
        if (demanderData.getElectronicSealUrl() != null && !"".equals(demanderData.getElectronicSealUrl())) {
            demanderSeal = demanderData.getElectronicSealUrl();
            demanderSeal = demanderSeal.split("/profile/upload")[1];
            try {
                demanderSeal = Util.encodeToString(RuoYiConfig.getUploadPath() + demanderSeal);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
//            if (demanderData.getSealUrl() != null && !"".equals(demanderData.getSealUrl())) {
//                demanderSeal = demanderData.getSealUrl();
//                try {
//                    demanderSeal = Util.encodeToString(RuoYiConfig.getDownloadPath() + demanderSeal);
//                    String downloadPath = RuoYiConfig.getDownloadPath();
//                    File file = new File(downloadPath);
//                    if (!file.exists()) {
//                        file.mkdir();
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            } else {
////                //生成电子印章到服务器
////                //自动生成一个印章 上传到服务器上
////                String socialCreditCode = demanderData.getSocialCreditCode();
////                String imgname = socialCreditCode + ".png";
////                String downloadPath = RuoYiConfig.getDownloadPath();
////                File file = new File(downloadPath);
////                if (!file.exists()) {
////                    file.mkdir();
////                }
////
////                File pngfile = new File(downloadPath + "/seal");
////                if (!pngfile.exists()) {
////                    pngfile.mkdir();
////                }
////                String path = downloadPath + "seal/" + imgname;
////                //生成 印章照片
////                try {
////                    SealUtils.toSeal(iSysDeptService.selectDeptById(demanderData.getCompanyId()).getDeptName(), demanderData.getSocialCreditCode(), path);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                }
////                Company company3 = new Company();
////                company3.setSealUrl("/seal/" + imgname);
////                company3.setCompanyId(demanderData.getCompanyId());
////                demanderSeal = "/seal/" + imgname;
////                //更新url
////                iCompanyServer.updateCompany(company3);
//            }
////            try {
////                demanderSeal = Util.encodeToString(RuoYiConfig.getDownloadPath() + demanderSeal);
////            } catch (IOException e) {
////                e.printStackTrace();
////            }
        }
        if (!demanderSeal.equals("")) {
            jsonObject.put("demanderSeal", "data:image/jpg;base64," + demanderSeal);
        }

        //邮编

        //电话
//        jsonObject.put("demanderPhone", demanderInvoiceData.getCorporateRegisterPhone());
        jsonObject.put("demanderPhone", companyLinkman.getPhoneNum());
        //统一社会信用代码
        jsonObject.put("demanderSocialCreditCode", demanderData.getSocialCreditCode());
        //开户
        jsonObject.put("demanderBank", demanderInvoiceData.getDepositBank());
        //账号
        jsonObject.put("demanderBankNum", demanderInvoiceData.getBankNumber());
        //签约代表
//        jsonObject.put("demanderCustomerForStaff", demanderData.getCorporateRepresentative());
        jsonObject.put("demanderCustomerForStaff", companyLinkman.getName());

        return jsonObject;
    }


}
